<template>
  <div class="mini-window"
       :class="{ 'expanded': isExpanded }"
       @mousedown="handleMouseDown"
       @mouseenter="handleMouseEnter"
       @mouseleave="handleMouseLeave">
    <!-- 折叠状态 -->
    <div class="mini-content">
      <span class="mini-bg"></span>
    </div>
    <!-- 展开状态 -->
    <div class="expanded-content" @click.stop>
      <div class="actions">
        <div class="action-item" @click="handleAction('restore')">
          <span>还原</span>
        </div>
        <div class="action-item" @click="handleAction('settings')">
          <span>设置</span>
        </div>
        <div class="action-item" @click="handleAction('dashboard')">
          <span>仪表盘</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { throttle } from 'lodash';
import eventBus from "@/utils/mitt.js";
const isExpanded = ref(false)
let isDragging = false
let initialMouseX = 0
let initialMouseY = 0
let mouseDownTime = 0
let windowInitialX = 0
let windowInitialY = 0

// 获取屏幕信息
const getScreenInfo = async () => {
  const screenInfo = await window.electronAPI.invoke('getScreenInfo');
  return screenInfo?.workAreaSize || { width: 0, height: 0 };
};

// 节流化的位置发送
const throttledSendPosition = throttle((x, y) => {
  window.electronAPI.send('setPosition', { x, y });
}, 50);

// 处理鼠标按下事件
const handleMouseDown = async (e) => {
  if (isExpanded.value) return // 展开状态不允许拖动
  isDragging = false
  initialMouseX = e.screenX // 使用screenX/screenY获取相对于屏幕的坐标
  initialMouseY = e.screenY
  mouseDownTime = Date.now()
  // 修正：通过 IPC 获取实时窗口位置
  const { x: winX, y: winY } = await window.electronAPI.invoke('getPosition');
  windowInitialX = winX;
  windowInitialY = winY;
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 处理鼠标移动事件
const handleMouseMove = async (e) => {
  const deltaX = e.screenX - initialMouseX
  const deltaY = e.screenY - initialMouseY

  // 判断是否达到拖动阈值
  if (!isDragging && (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5)) {
    isDragging = true
  }

  if (isDragging) {
    // 计算新位置
    const newX = windowInitialX + deltaX
    const newY = windowInitialY + deltaY

    // 动态获取屏幕边界
    const { width: screenWidth, height: screenHeight } = await getScreenInfo();
    const [winWidth, winHeight] = await window.electronAPI.invoke('get-window-size');
    // 发送新位置到主进程
    const clampedX = Math.max(0, Math.min(newX, screenWidth - winWidth));
    const clampedY = Math.max(0, Math.min(newY, screenHeight - winHeight));
    throttledSendPosition(clampedX, clampedY);
  }
}

const handleMouseUp = () => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)

  // 如果不是拖拽且点击时间小于200ms，则触发展开/收起
  if (!isDragging && (Date.now() - mouseDownTime < 200)) {
    toggleExpand()
  }
}

const handleMouseEnter = () => {
}

const handleMouseLeave = () => {
}

const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}
const handleAction = (action) => {
  switch (action) {
    case 'restore':
      window.electronAPI.send('showFloatBall', {
        width: 90,
        height: 90,
        turnIntoABall: false
      })
      break
    case 'dashboard':
      window.electronAPI.send('showMessage', {
        type: 'info',
        message: '打开仪表盘',
      })
      break
    case 'settings':
      window.electronAPI.send('showMessage', {
        type: 'info',
        message: '打开设置',
      })
      break
  }
  isExpanded.value = false
}

onMounted(() => {
})
</script>

<style scoped lang="scss">
.mini-window {
  position: relative;
  margin-top: 100px;
  margin-left: 125px;
  width: 70px;
  height: 70px;
  border-radius: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  overflow: hidden;
  user-select: none;

  &.expanded {
    width: 160px;
    height: 150px;
    border-radius: 12px;
    transform: translate(-110px, -100px);

    .mini-content {
      opacity: 0;
      pointer-events: none;
    }

    .expanded-content {
      opacity: 1;
      pointer-events: auto;
    }
  }

  .mini-content {
    position: absolute;
    bottom: 1px;
    right: 5px;
    opacity: 1;
    transition: opacity  0.3s;
    .mini-bg {
      cursor: pointer;
      display: inline-block;
      width: 60px;
      height: 60px;
      border-radius: 20px;
      transition: transform 0.3s;
      background: url("https://ssc.homedo.com/static/gif/flower-d1d9a04c.gif") no-repeat center top / cover;
      &:hover {
        transition: transform 0.3s;
        transform: scale(1.1);
      }
    }
  }

  .expanded-content {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 160px;
    height: 150px;
    opacity: 0;
    padding: 9px 12px;
    pointer-events: none;
    transition: opacity 0.3s;
    background: #FFFFFF;

    .actions {
      display: flex;
      flex-direction: column-reverse;
      gap: 8px;

      .action-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 10px 12px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        color: #222222;

        .el-icon {
          font-size: 18px;
        }

        span {
          font-size: 14px;
        }

        &:hover {
          background-color: var(--menu-active-bg-color);
          transform: scale(1.06);
          outline: 1px solid var(--ep-color-primary);
        }
      }
    }
  }
}
</style>
